package com.lin.algorithm.alo0518;

import com.alibaba.fastjson.JSON;

public class PlusOne {
    public static void main(String[] args) {
        System.out.println("JSON.toJSONString(plusOne(new int[]{0})) = " + JSON.toJSONString(plusOne(new int[]{0})));
        System.out.println("JSON.toJSONString(plusOne(new int[]{1,2,3})) = " + JSON.toJSONString(plusOne(new int[]{1, 2, 3})));
        System.out.println("JSON.toJSONString(plusOne(new int[]{4,3,2,1})) = " + JSON.toJSONString(plusOne(new int[]{4, 3, 2, 1})));
        System.out.println("JSON.toJSONString(plusOne(new int[]{8,9,9,9})) = " + JSON.toJSONString(plusOne(new int[]{8, 9, 9, 9})));
        System.out.println("JSON.toJSONString(plusOne(new int[]{9,9,9,9})) = " + JSON.toJSONString(plusOne(new int[]{9, 9, 9, 9})));

    }

    public static int[] plusOne(int[] digits) {
        // 边界判断
        if (digits == null || digits.length == 0) {
            return null;
        }
        int offset = digits.length - 1;

        while (offset >= 0) {
            if (digits[offset] + 1 == 10) {
                digits[offset] = 0;
                offset--;
            } else {
                digits[offset] = digits[offset] + 1;
                return digits;
            }
        }
        int[] rs = digits;
        if (offset < 0) {
            rs = new int[digits.length + 1];
            rs[0] = 1;
        }
        return rs;
    }
}
